export * from "./mws";
import { existUni } from "./mws";

interface EventBusHandle {
  type: string;
  callBack: (data: any) => void;
}
export class EventBus {
  public readonly create: (type: string, callBack: (data: any) => any) => void;
  public readonly arrival: (type: string, data?: any) => void;
  public readonly remove: (type?: string, callback?: cbk) => void;
  constructor () {
    if (existUni()) {
      this.create = (type, cbk) => {
        uni.$on(type, cbk);
      };
      this._arrival = (type, data) => {
        console.log(...arguments);
        uni.$emit(type, data);
      };
      this.remove = (type, cbk) => {
        uni.$off(type, cbk);
      };
    }
    this.create = this._create;
    this.arrival = this._arrival;
    this.remove = this._remove;
  }
  private readonly hs: EventBusHandle[] = [];
  private _create(type: string, callBack: (data: any) => any) {
    if (type && callBack instanceof Function) {
      this.hs.push({ type, callBack });
    }
  }
  private _arrival(type: string, data?: any) {
    for (const e of this.hs) {
      if (new RegExp(e.type).test(type)) {
        try { e.callBack(data); } catch (_) { }
      }
    }
  }
  private _remove(type?: string, callback?: cbk) {
    let i = this.hs.length;
    if (type || callback) {
      if (type && callback) {
        while (i--) {
          if (this.hs[i].callBack === callback && this.hs[i].type === type) {
            this.hs.splice(i, 1);
          }
        }
      } else {
        while (i--) {
          if (this.hs[i].callBack === callback || this.hs[i].type === type) {
            this.hs.splice(i, 1);
          }
        }

      }
    } else {
      this.hs.splice(0);
    }
  }
}